(function($, window, undefined) {
    $.EtFile = $.EtFile || {};
	$.EtFile.list = {};
	
	$.extend($.EtFile, {
        "version": "1.0.0",
		//定义外部扩展方法接口
        "extend": function(methods) {
            $.extend($.fn.EtFile, methods);
			
			if (!this.no_legacy_api) {
				$.fn.extend(methods);
			}
        },
		"randomString" : function(length) {
			var chars = 'abcdefghiklmnopqrstuvwxyz'.split('');
			 
			if (! length) {
				 length = Math.floor(Math.random() * chars.length);
			 }
			 
			var str = '';
			 for (var i = 0; i < length; i++) {
				 str += chars[Math.floor(Math.random() * chars.length)];
			 }
			 return str;
		 }
    });
	
	//常用扩展方法
	$.EtFile.extend({
		getChecked : function(){
			var val = '';
			$(this).find('.et_tbody .chk_item:checked').each(function(index, element) {
				if(val){
					val += ','+$(this).val();
				}else{
					val += $(this).val();
				}
			});
			
			return val;
		},
		refresh : function(){
			getList(this);
		},
		layout : function(){
			et_layout(_this);
		},
		search : function(){
			getList(this);
		}
    });
	
	
	$.fn.EtFile = function(options) {
        var _this = this;

		//合并参数
        var config = $.extend({},$.fn.EtFile.defaults, options);
        
		//内部扩展
		var bosom = {
		};

		_this.bosom = bosom;
		_this.config = config;
		
		//初始化
		init(_this);
		
		if(_this.config.gridId){
		}else{
			_this.config.gridId = $.EtFile.randomString(8);
		}
		
		$.EtFile.list[_this.config.gridId] = _this;
		
		//当窗口大小变化时，重新计算布局
		$(window).on('resize',function(){
			et_layout(_this);
		});
		
		return _this;
    };
	
	$.fn.EtFile.defaults = {
		gridId:'',
		jsonUrl: '', //数据获取地址
		blockBox: '', //数据容器选择器
		blockBoxWidth: '', //数据容器宽度
		adaptiveFixedWidth: '', //自适应宽度要减去的固定尺寸
		adaptiveFixedHeight: '', //自适应高度要减去的固定尺寸
		blockBoxHeight: '', //数据容器高度
		hasTool : false, //是否有工具条
		where: '', //查询条件
		pageNum: 20, //每页显示条数
		pageNums: '10,20,30,40,50', //每页显示条数可选项
		nowPage: 1, //当前页
		allPage: 0, //总页数
		orderField: 'id', //排序字段
		orderDirection: 'desc', //排序方向
		dataContextMenuOpen: false, //是否开启数据行右键菜单
		dataContextMenu: function(){}, //数据行右键菜单
		connection: false, //当前是否在进行Ajax通讯
		showPageNav: true, //是否显示分页导航
		colModel : [
			{
				display : 'checkbox',
				name : 'id',
				sortable : false,
				myclass : 'center',
				edit : false
			}
		]
    };
	
	/**************************私有方法开始***************************/
	//初始化方法
	function init(_this){
		var _that = _this;
		var html = '';
		_that.html('<div class="loading"></div>');
		
		html += et_thead(_that); //获取头部
		html += et_tbody(_that); //获取列表
		html += et_tfoot(_that); //获取底部
		
		_that.html(html); //初始化界面
		eventBindBefore(_that); //绑定初始化界面事件
		getList(_that); //获取数据
	}
	
	//数据列表样式调整
	function et_layout(_this){
		var _that = _this;
			
		_that.find('.et_tbody>table tr:odd').addClass('deep');
		
		var colModelObj = _that.config.colModel;
		
		if(_that.config.blockBoxWidth && _that.config.blockBoxWidth!=''){			
			var blockBoxWidth = _that.config.blockBoxWidth;
			if(_that.config.blockBoxWidth == 'window'){
				blockBoxWidth = $(window).width();
			}
			if(_that.config.blockBoxWidth == 'adaptive'){
				blockBoxWidth = $(window).width()-_that.config.adaptiveFixedWidth;
			}
			
			_that.width(blockBoxWidth);
		}
		if(_that.config.blockBoxHeight && _that.config.blockBoxHeight!=''){
			var blockBoxHeight = _that.config.blockBoxHeight;
			if(_that.config.blockBoxHeight == 'adaptive'){
				blockBoxHeight = $(window).height()-_that.config.adaptiveFixedHeight;
			}else if(_that.config.blockBoxHeight == 'window'){
				blockBoxHeight = $(window).height();
				//console.log(blockBoxHeight);
				if($('.page_header').length>0){
					blockBoxHeight = blockBoxHeight-$('.page_header').height()-7;
				}
			}
			
			_that.height(blockBoxHeight);
		}
		_that.children('.et_tbody').height(_that.height()-65);
		
		//计算宽度
		if(_that.config.widthType=='thw'){
			var width = _that.width()-18;
			_that.find('.et_thead table').css('width',width+'px');
			_that.find('.et_thead table').css('margin-right','18px');
			
			for(var i=0; i<colModelObj.length ; i++){
				if(colModelObj[i].width){
					//console.log($('.et_thead>table tr>th[fieldname="'+colModelObj[i].name+'"]'));
					_that.find('.et_thead>table tr>th[fieldname="'+colModelObj[i].name+'"]').css('width',colModelObj[i].width);
				}				
			}
			
			_that.find('.et_thead>table tr:eq(0)>th').each(function(index, element) {
				_that.find('.et_tbody>table tr:eq(0)>td').eq(index).width($(this).width());
			});
		}else if(_that.config.widthType=='tdw'){
			_that.find('.et_thead table').css('width','auto');
			
			for(var i=0; i<colModelObj.length ; i++){
				if(colModelObj[i].width){
					_that.find('.et_tbody>table tr:eq(0)>td[fieldname="'+colModelObj[i].name+'"]').css('width',colModelObj[i].width);
				}				
			}
			
			_that.find('.et_tbody>table tr:eq(0)>td').each(function(index, element) {
				_that.find('.et_thead>table tr>th').eq(index).width($(this).width());
			});	
		}else{
			_that.find('.et_thead table').css('width','auto');
			
			_that.find('.et_tbody>table tr:eq(0)>td').each(function(index, element) {
				_that.find('.et_thead>table tr>th').eq(index).width($(this).width());
			});
		}
	}
	
	//创建表头
	function et_thead(_this){
		var _that = _this;
		var html = '';			
		var colModelObj = _that.config.colModel;
		
		html += '<div class="et_thead">';
		html += '<table width="0" border="0" cellspacing="0" cellpadding="0">';
		html += '<tr>';
		
		for(var i=0; i<colModelObj.length ; i++){
			if(colModelObj[i].display == 'checkbox'){
				html += '<th fieldname="'+colModelObj[i].name+'"><input type="checkbox" class="chk_all" value="ok"/></th>';
			}else{
				var css = '';
				if(colModelObj[i].sortable){
					css = 'sort';
				}
				
				if(_that.config.orderName == colModelObj[i].name){
					if(_that.config.orderDirection=='asc'){
						css += ' sort_asc';
					}else{
						css += ' sort_desc';
					}
				}
				css += ' '+colModelObj[i].myclass;
				
				html += '<th class="'+css+'" fieldname="'+colModelObj[i].name+'">'+colModelObj[i].display+'</th>';							
			}
			
		}
		html += '</tr>';
		html += '</table>';
		html += '</div>';
		
		return html;
	}
	
	//创建表体
	function et_tbody(_this){
		var _that = _this;
		var html = '';
		
		html += '<div class="et_tbody">';
		html += '</div>';
		
		return html;
	}
	
	//创建表尾
	function et_tfoot(_this){
		var _that = _this;
		var html = '';
		
		//console.log(_that);
		
		html += '<div class="et_tfoot clearfix">';
		html += '<div class="page_select">';
		html += '当前选择了<span>0</span>条记录';
		html += '</div>';
		
		if(_that.config.showPageNav){
			html += '<ul class="pagenav clearfix">';

			if(_that.config.nowPage==1){
				html += '<li class="page_first disabled">';
			}else{
				html += '<li class="page_first">';
			}
			
			html += '<i class="icon-step-backward"></i>';
			html += '</li>';
			
			if(_that.config.nowPage==1){
				html += '<li class="page_prev disabled">';
			}else{
				html += '<li class="page_prev">';
			}
			
			html += '<i class="icon-chevron-left"></i>';
			html += '</li>';
			html += '<li class="page_now">';
			html += '当前为第<input type="text" id="pagenow" value="'+_that.config.nowPage+'"/>页 共<span>'+_that.config.allPage+'<span>页';
			html += '</li>';
			
			if(_that.config.nowPage==_that.config.allPage){
				html += '<li class="page_next disabled">';
			}else{
				html += '<li class="page_next">';
			}
			
			html += '<i class="icon-chevron-right"></i>';
			html += '</li>';
			
			if(_that.config.nowPage==_that.config.allPage){
				html += '<li class="page_last disabled">';
			}else{
				html += '<li class="page_last">';
			}
			
			html += '<i class="icon-step-forward"></i>';
			html += '</li>';
			html += '<li class="page_nums">';
			html += '每页';
			html += '<select name="pagenum">';
			
			var pageNums_arr = _that.config.pageNums.split(',');
			for(var i=0; i<pageNums_arr.length ; i++){
				var selected = '';
				if(_that.config.pageNum == pageNums_arr[i]){
					selected = 'selected="selected"';
				}
				html += '<option value="'+pageNums_arr[i]+'" '+selected+'>'+pageNums_arr[i]+'</option>';
			}
			
			html += '</select>';
			html += '条';
			html += '</li>';
			html += '<li class="page_refresh">';
			html += '<i class="icon-refresh"></i>';
			html += '</li>';
			html += '</ul>';
			html += '</div>';
		}
		html += '</div>';
		
		return html;
	}
	
	//异步加载数据
	function getList(_this){
		var _that = _this;
		
		//console.log(_that);
		
		if(_that.config.connection){
			return false;
		}else{
			_that.config.connection = true;
		}
		
		var html = '';
		var colModelObj = _that.config.colModel;
		
		//先显示正在加载图标
		_that.children('.et_tbody').html('<div class="loading"></div>');
		
		$.get(
			_that.config.jsonUrl,
			{
				where: escape(_that.config.where),
				pageNum: _that.config.pageNum,
				nowPage: _that.config.nowPage,
				orderName: _that.config.orderName,
				orderDirection: _that.config.orderDirection,
				rnd: Math.random()
			},
			function(data){
				//console.log(data);
				_that.config.nowPage = data.page;
				_that.config.allPage = data.totalPage;
				
				if($.isEmptyObject(data.rows)){
					html += '<div class="emptyData">没有找到相关数据</div>';
					
					_that.children('.et_tbody').html(html);
					_that.children('.et_tfoot').html(et_tfoot(_that));
					_that.config.connection = false;
					
					et_layout(_that); //重新调整布局样式				
				}else{
					html += '<table width="0" border="0" cellspacing="0" cellpadding="0">';
					for(var j=0; j<data.rows.length ; j++){
						html += '<tr rowid="'+data.rows[j]['id']+'">';
						for(var k=0; k<colModelObj.length ; k++){
							if(colModelObj[k].display == 'checkbox'){
								html += '<td fieldname="'+colModelObj[k].name+'"><input type="checkbox" class="chk_item" name="'+colModelObj[k].name+'" value="'+data.rows[j][colModelObj[k].name]+'"/></td>';
							}else{								
								html += '<td fieldname="'+colModelObj[k].name+'" class="'+colModelObj[k].myclass+'">'+data.rows[j]['cell'][colModelObj[k].name]+'</td>';			
							}
						}
						html += '</tr>';
					}
					html += '</table>';
					
					//return html;
					//console.log(html);					
					_that.children('.et_tbody').html(html);
					_that.children('.et_tfoot').html(et_tfoot(_that));
					
					et_layout(_that); //重新调整布局样式
					eventBindAfter(_that); //绑定插件内事件
					
					_that.config.connection = false;
				}
			},
			'json'
		);
	}
	
	//插件内事件绑定
	function eventBindBefore(_this){
		var _that = _this;
		
		//数据行右键编辑
		if(_that.config.dataContextMenuOpen){
			_that.config.dataContextMenu();
		}
		
		//排序
		_that.find('.et_thead .sort').on('click',function(){
			if(_that.config.connection){
				return false;
			}
			
			var fieldname = $(this).attr('fieldname');
			
			_that.config.orderField = fieldname; //排序字段
			
			if($(this).is('.sort_asc')){
				_that.config.orderDirection = 'asc'; //排序方向
				_that.find('.et_thead .sort').removeClass('sort_asc').removeClass('sort_desc');				
				$(this).addClass('sort_desc');
			}else{
				_that.config.orderDirection = 'desc'; //排序方向
				_that.find('.et_thead .sort').removeClass('sort_asc').removeClass('sort_desc');
				$(this).addClass('sort_asc');
			}
			
			getList(_that);
		});
		
		
		//选择/取消选择
		_that.find('.et_thead .chk_all').on('click',function(){
			if($(this).is(':checked')){
				_that.find('.et_tbody .chk_item').prop('checked','checked');
			}else{
				_that.find('.et_tbody .chk_item').prop('checked','');
			}
			
			checkboxDeal(_that);
		});
	}
	
	function eventBindAfter(_this){
		var _that = _this;
		
		//选择单项
		_that.find('.et_tbody .chk_item').on('click',function(evt){
			checkboxDeal(_that);
		});
		
		if(_that.config.showPageNav){
			//第一页
			_that.find('.et_tfoot .page_first').on('click',function(){
				if(_that.config.connection){
					return false;
				}
				

				_that.config.nowPage = 1;
				getList(_that);
			});
			//最后页
			_that.find('.et_tfoot .page_last').on('click',function(){
				if(_that.config.connection){
					return false;
				}
				
				_that.config.nowPage = _that.config.allPage;
				getList(_that);
			});
			//上一页
			_that.find('.et_tfoot .page_prev').on('click',function(){
				if(_that.config.connection){
					return false;
				}
				
				if(_that.config.nowPage<=1){
					return false;
				}
				_that.config.nowPage = _that.config.nowPage-1;
				getList(_that);
			});
			//下一页
			_that.find('.et_tfoot .page_next').on('click',function(){
				if(_that.config.connection){
					return false;
				}
				
				if(_that.config.nowPage>=_that.config.allPage){
					return false;
				}
				_that.config.nowPage = _that.config.nowPage+1;
				getList(_that);
			});
			//刷新
			_that.find('.et_tfoot .page_refresh').on('click',function(){
				if(_that.config.connection){
					return false;
				}
				
				getList(_that);
			});
			
			//修改每页显示数量
			_that.find('.et_tfoot select[name="pagenum"]').on('change',function(){
				if(_that.config.connection){
					return false;
				}
				
				_that.config.pageNum = $(this).val();
				_that.config.nowPage = 1;
				getList(_that);
			});
			
			//修改当前页码
			_that.find('.et_tfoot .page_now input').on('change',function(){
				if(_that.config.connection){
					return false;
				}
				
				var num = $(this).val();
				if(!isNaN(num)){
					return false;
				}
				if(num<1){
					num=1;
				}
				if(num>_that.config.allPage){
					num=_that.config.allPage;
				}
				
				_that.config.nowPage = num;
				getList(_that);
			});
		}
	}
	
	//复选框改变后的响应
	function checkboxDeal(_this){
		var _that = _this;
		var chk_num = _that.find('.chk_item:checked').length;
		_that.find('.et_tfoot>.page_select>span').html(chk_num);
		
		_that.find('.chk_item').each(function(index, element) {
			if($(this).is(':checked')){
				$(this).parent('td').parent('tr').addClass('select');
			}else{
				$(this).parent('td').parent('tr').removeClass('select');
			}
		});
	}
})(jQuery, window);